use param_parser::parse_param_by_file_name;
use shq_common::prelude::del_rept_tmp_talbe_in_ch;

use crate::{get_excel_import_config};

mod category;
mod excel_reader;
mod param_parser;
mod table_data;

pub async fn import_excel_by_bytes(bytes: Vec<u8>, file_name: &str) -> anyhow::Result<()> {
    let conf = get_excel_import_config()
        .find_by_file_name(file_name)
        .ok_or(anyhow::anyhow!("未找到文件{file_name}对应的配置"))?;
    let mut pval = 0;
    let psval;
    let mut params: Vec<(&str, &str)> = vec![];
    if !conf.param_name.is_empty() {
        pval = parse_param_by_file_name(file_name, conf.date_after.as_str(), conf.param_type)?;
        psval = pval.to_string();
        params = vec![(conf.param_name.as_str(), psval.as_str())];
    }
    let conf_name = conf
        .get_config_name(pval)
        .ok_or(anyhow::anyhow!("对应参数{pval}配置未找到"))?;
    let reader = excel_reader::ExcelReader::new(conf_name)?;
    reader.read_excel_by_bytes(bytes, &params).await?;
    del_rept_tmp_talbe_in_ch(&conf.rept_names).await?;
    Ok(())
}

pub async fn import_excel_with_conf(
    bytes: Vec<u8>,
    conf_name: &str,
    params: Vec<(&str, &str)>,
) -> anyhow::Result<()> {
    let reader = excel_reader::ExcelReader::new(conf_name)?;
    reader.read_excel_by_bytes(bytes, &params).await?;
    Ok(())
}

pub async fn import_excel_by_conf(file_path: &str) -> anyhow::Result<()> {
    let file_name = std::path::Path::new(file_path)
        .file_name()
        .ok_or(anyhow::anyhow!("未指定文件名"))?
        .to_str()
        .ok_or(anyhow::anyhow!("未指定文件名"))?;
    let conf = get_excel_import_config()
        .find_by_file_name(file_name)
        .ok_or(anyhow::anyhow!("未找到文件{file_name}对应的配置"))?;
    let pval = if conf.param_name.is_empty() {
        0
    } else {
        parse_param_by_file_name(file_name, conf.date_after.as_str(), conf.param_type)?
    };
    let conf_name = conf
        .get_config_name(pval)
        .ok_or(anyhow::anyhow!("对应参数{pval}配置未找到"))?;
    let psval = pval.to_string();
    let params = if conf.param_name.is_empty() {
        vec![]
    } else {
        vec![(conf.param_name.as_str(), psval.as_str())]
    };
    let reader = excel_reader::ExcelReader::new(conf_name)?;
    reader.read_excel_by_file_path(file_path, &params).await?;
    del_rept_tmp_talbe_in_ch(&conf.rept_names).await?;
    Ok(())
}

pub async fn import_by_excel(
    conf_name: &str,
    file_path: &str,
    params: &[(&str, &str)],
) -> anyhow::Result<()> {
    let reader = excel_reader::ExcelReader::new(conf_name)?;
    reader.read_excel_by_file_path(file_path, params).await?;
    Ok(())
}
